using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Utilities;

namespace Utilities
{
   public partial class UserDetails : Form
   {
      //////////////////////////////////////////////////////////////////////////
      //
      private static Logger logger_ = new Logger();
      private string userId_ = "";
      private string password_ = "";
      private string serverList_ = "localhost";
      private bool saveDetails_ = true;

      ////////////////////////////////////////////////////////////////////////
      //
      public UserDetails()
      {
         InitializeComponent();
      }

      ////////////////////////////////////////////////////////////////////////
      //
      private void btnOK_Click(object sender, EventArgs e)
      {
         try
         {
            SaveDetails = chkSaveDetails.Checked;
            UserId = txtUserId.Text.Trim();
            Password = txtPassword.Text.Trim();

            List<string> servers = new List<string>();
            string activeServer = cbLoginServer.Text.Trim();
            StringBuilder buildList = new StringBuilder(activeServer);
            foreach (object listItem in cbLoginServer.Items)
            {
               string thisItem = listItem.ToString();
               if (thisItem != activeServer)
               {
                  buildList.Append(',');
                  buildList.Append(thisItem);
               }
            }
            ServerList = buildList.ToString();
            DialogResult = DialogResult.OK;
            Close();
         }
         catch (System.Exception ex)
         {
            logger_.Exception(ex);
         }
      }

      ////////////////////////////////////////////////////////////////////////
      //
      private void UserDetails_Shown(object sender, EventArgs e)
      {
         try
         {
            chkSaveDetails.Checked = SaveDetails;
            txtUserId.Text = UserId.Trim();
            txtPassword.Text = Password.Trim();

            cbLoginServer.BeginUpdate();
            string[] servers = serverList_.Split(',', ';');
            cbLoginServer.Items.AddRange(servers);
            if (0 < cbLoginServer.Items.Count)
            {
               cbLoginServer.Text = servers[0];
               cbLoginServer.SelectedIndex = 0;
            }
            cbLoginServer.EndUpdate();

            CheckButtons();
         }
         catch (System.Exception ex)
         {
            logger_.Exception(ex);
         }
      }

      ////////////////////////////////////////////////////////////////////////
      //
      private void CheckButtons()
      {
         try
         {
            btnOK.Enabled = !string.IsNullOrWhiteSpace(txtUserId.Text)
               && !string.IsNullOrWhiteSpace(cbLoginServer.Text);
         }
         catch (System.Exception ex)
         {
            logger_.Exception(ex);
         }
      }

      ////////////////////////////////////////////////////////////////////////
      //
      private void txtUserId_TextChanged(object sender, EventArgs e)
      {
         try
         {
            CheckButtons();
         }
         catch (System.Exception ex)
         {
            logger_.Exception(ex);
         }
      }

      ////////////////////////////////////////////////////////////////////////
      //
      private void cbLoginServer_TextChanged(object sender, EventArgs e)
      {
         try
         {
            CheckButtons();
         }
         catch (System.Exception ex)
         {
            logger_.Exception(ex);
         }
      }

      //////////////////////////////////////////////////////////////////////////
      //
      public static DialogResult GetUserId(IWin32Window parent, string title, Configuration config,
         bool autoLogin, out string userId, out string password, out string loginServer)
      {
         userId = password = loginServer = string.Empty;
         try
         {
            // Get the userId / password to use from the configuration
            Config.Utilities settings = config.GetSection(Config.Utilities.CONFIG_SECTION) as Config.Utilities;
            userId = settings.UserId;
            password = settings.Password;
            string[] servers = settings.ServerList.Value.Split(',', ';');
            if (0 < servers.Length)
            {
               // The default server is the first one in the list
               loginServer = servers[0];
            }

            // If there is no parent window, we cannot prompt for user confirmation
            // so we run with what's in the app.config
            if (null == parent)
            {
               // can't ask the user, we use the config settings
               return string.IsNullOrWhiteSpace(userId) ? DialogResult.Abort : DialogResult.OK;
            }
            if (!string.IsNullOrWhiteSpace(userId))
            {
               DialogResult result = autoLogin ? DialogResult.Yes
                  : MessageBox.Show(parent, "Do you want to use the same userId/password that you used last time?",
                     string.Concat(title, ": a saved user-id/password was detected"), MessageBoxButtons.YesNoCancel);
               if (DialogResult.Yes == result)
               {
                  return DialogResult.Yes;
               }
               if (DialogResult.Cancel == result)
               {
                  return DialogResult.Cancel;
               }
               userId = password = string.Empty;
            }

            // Prompt the use for the login details
            UserDetails dlg = new UserDetails();
            dlg.Text = String.Concat(title, " - login details");
            if (false != (dlg.SaveDetails = settings.SaveLoginDetails))
            {
               dlg.UserId = settings.UserId;
               dlg.Password = settings.Password;
               dlg.ServerList = settings.ServerList;
            }
            if (DialogResult.OK == dlg.ShowDialog(parent))
            {
               userId = dlg.UserId;
               password = dlg.Password;
               loginServer = dlg.ServerList.Split(';', ',')[0];
               if (false != (settings.SaveLoginDetails.Value = dlg.SaveDetails))
               {
                  settings.UserId.Value = userId;
                  settings.Password.Value = password;
                  settings.ServerList.Value = dlg.ServerList;
                  config.Save(ConfigurationSaveMode.Full);
               }
               return DialogResult.OK;
            }
         }
         catch (System.Exception ex)
         {
            logger_.Exception(ex);
         }
         return DialogResult.Abort;
      }

      ////////////////////////////////////////////////////////////////////////
      //
      public bool SaveDetails { get { return saveDetails_; } set { saveDetails_ = value; } }
      public string UserId { get { return userId_; } set { userId_ = value; } }
      public string Password { get { return password_; } set { password_ = value; } }
      public string ServerList { get { return serverList_; } set { serverList_ = value; } }
   }
}
